#include "uploadthread.h"

#include <iostream>
using std::cout;
using std::endl;

#include <string>
using std::string;

#include <Poco/Thread.h>
using Poco::Thread;

#include <Poco/Net/StreamSocket.h>
using Poco::Net::StreamSocket;

#include <Poco/FileStream.h>
using Poco::FileInputStream;

#include <Poco/Net/SocketStream.h>
using Poco::Net::SocketStream;

#include <Poco/StreamCopier.h>
using Poco::StreamCopier;

#include <Poco/Net/SocketAddress.h>
using Poco::Net::SocketAddress;

#define RETRIES 10

namespace Commands {

	UploadThread::UploadThread(string host, UInt16 port, string filename) :
		_host(host),
		_port(port),
		_file(filename)
	{
		cout << "UploadThread :: creating UploadThread for \"" << _file.path() << "\" (" << _file.getSize() << ")" << endl;
	}

	void UploadThread::run()
	{
		cout << "UploadThread :: Starting upload process " << endl;
		int retries = RETRIES;
		bool sent = false;

		FileInputStream fin(_file.path());
		SocketAddress address(_host,_port);
		while (retries > 0 && !sent)
		{
			cout << "UploadThread :: Trying to contact " << _host << ":" << _port << endl;
			try {
				StreamSocket socket(address);
				SocketStream sout(socket);
				StreamCopier::copyStream(fin,sout);

				cout << "UploadThread :: Upload succeeded" << endl;
				sent = true;
			} catch (...) {
				cout << "UploadThread :: Upload failed, trying again, " << retries << " tries left" << endl;
			}
			--retries;
		}
	}
}
